import 'package:flutter_test1/model/account_model.dart';

import 'base_table.dart'; // 假设你的 BaseTable 定义在 base_table.dart 文件中

class AccountTable extends BaseTable {
  @override
  String get tableName => 'accounts';

  @override
  String get createTableSQL => '''
    CREATE TABLE accounts(
      id INTEGER PRIMARY KEY, 
      ethereum_address TEXT, 
      eth_tail INTEGER,
      tron_address TEXT, 
      tron_tail INTEGER,
      bitcoin_address TEXT, 
      private_key TEXT, 
      public_key TEXT
    )
  ''';

  /// 插入新账户
  Future<int> insertAccount({
    required String ethereumAddress,
    required int ethTail,
    required String tronAddress,
    required int tronTail,
    required String bitcoinAddress,
    required String privateKey,
    required String publicKey,
  }) async {
    return await insert({
      'ethereum_address': ethereumAddress,
      'eth_tail': ethTail,
      'tron_address': tronAddress,
      'tron_tail': tronTail,
      'bitcoin_address': bitcoinAddress,
      'private_key': privateKey,
      'public_key': publicKey,
    });
  }

  /// 查询所有账户
  Future<List<AccountModel>> getAllAccounts() async {
    List<Map<String, dynamic>> res = await query();
    return res.map((e) => AccountModel.fromJson(e)).toList();
  }

  /// 获取按 eth_tail 降序排列的数据
  Future<List<AccountModel>> getAccountsSorted(String orderBy) async {
    List<Map<String, dynamic>> res = await query(orderBy: orderBy);
    return res.map((e) => AccountModel.fromJson(e)).toList();
  }

  /// 根据以太坊地址查询账户
  Future<List<Map<String, dynamic>>> getAccountByEthereumAddress(String ethereumAddress) async {
    return await query(
      where: 'ethereum_address = ?',
      whereArgs: [ethereumAddress],
    );
  }

  /// 根据账户 ID 更新数据
  Future<int> updateAccount({
    required int id,
    String? ethereumAddress,
    String? tronAddress,
    String? bitcoinAddress,
    String? privateKey,
    String? publicKey,
    int? ethTail,
    int? tronTail,
  }) async {
    final updateData = <String, dynamic>{};
    if (ethereumAddress != null) updateData['ethereum_address'] = ethereumAddress;
    if (tronAddress != null) updateData['tron_address'] = tronAddress;
    if (bitcoinAddress != null) updateData['bitcoin_address'] = bitcoinAddress;
    if (privateKey != null) updateData['private_key'] = privateKey;
    if (publicKey != null) updateData['public_key'] = publicKey;
    if (ethTail != null) updateData['eth_tail'] = ethTail;
    if (tronTail != null) updateData['tron_tail'] = tronTail;

    return await update(
      updateData,
      where: 'id = ?',
      whereArgs: [id],
    );
  }

  /// 根据账户 ID 删除账户
  Future<int> deleteAccountByPriKey(String privateKey) async {
    return await delete(
      where: 'private_key = ?',
      whereArgs: [privateKey],
    );
  }

  /// 删除所有账户
  Future<int> deleteAllAccounts() async {
    return await delete();
  }
}

